#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
const int N = 1e4 + 10, M = 1010;
int f[M];
int n, m;
int c[N], t[N], p[N];
int main()
{
    int t1, t2, t3, t4;
    char a;
    cin >> t1 >> a >> t2 >> t3 >> a >> t4 >> n;
    m = t3 * 60 + t4 - (t1 * 60 + t2);
    for (int i = 1; i <= n; i++)
    {
        cin >> t[i] >> c[i] >> p[i];
    }
    for (int i = 1; i <= n; i++)
    {
        if (p[i] == 0)
        {
            for (int j = t[i]; j <= m; j++)
            {
                f[j] = max(f[j], f[j - t[i]] + c[i]);
            }
        }
        else if (p[i] == 1)
        {
            for (int j = m; j >= t[i]; j--)
            {
                f[j] = max(f[j], f[j - t[i]] + c[i]);
            }
        }
        else
        {
            for (int j = m; j >= t[i]; j--)
            {
                for (int k = 1; k <= p[i] && t[i] * k <= j; k++)
                {
                    f[j] = max(f[j], f[j - k * t[i]] + c[i] * k);
                }
            }
        }
    }
    cout << f[m];
    return 0;
}